/*
 * @Author: 刘慧东
 * @Date: 2024-07-24 14:36:41
 * @LastEditors: 刘慧东
 * @LastEditTime: 2024-07-26 16:46:53
 */
package jrpc

import (
	"context"
	"fmt"
	"net"
	"net/http"
	"strings"

	"github.com/ybbus/jsonrpc/v3"
)

type Jclient struct {
	Client jsonrpc.RPCClient
}

type Response struct {
	*jsonrpc.RPCResponse
}

// address format: "localhost:1234"
func NewClient(address string) (*Jclient, error) {

	url := fmt.Sprintf("%s/%s", address, "rpc")
	// address是否包含unix://
	if strings.HasPrefix(address, "unix://") {
		address = strings.TrimPrefix(address, "unix://")
		http.DefaultClient.Transport = &http.Transport{
			DialContext: func(_ context.Context, network string, addr string) (net.Conn, error) {
				return net.Dial("unix", address)
			},
		}

		url = fmt.Sprintf("http://%s/%s", address, "rpc")
	}

	rpcClient := jsonrpc.NewClientWithOpts(url, &jsonrpc.RPCClientOpts{HTTPClient: http.DefaultClient})
	return &Jclient{
		Client: rpcClient,
	}, nil
}

func (j *Jclient) Close() {
}

func (j *Jclient) Call(ctx context.Context, method string, args ...any) (*Response, error) {
	res, err := j.Client.Call(ctx, method, args)
	if err != nil {
		return nil, err
	}

	return &Response{res}, nil
}
